<template>
  <div>
    <el-container>
      <el-header style="display: flex; align-items: center; padding: 10px;">
        <el-input
          v-model="kwInput"
          placeholder="输入 任意字符 进行筛选"
          class="input-with-select"
          clearable
          style="max-width: 250px; margin-right: 20px;"
          @keyup.native.enter="handleSearch"
        >
          <el-button
            slot="append"
            icon="el-icon-search"
            :loading="listLoading"
            @click="handleSearch"
          >
            搜索
          </el-button>
        </el-input>

        <!-- 选择账号 -->
        <el-select
          v-model="wc_id"
          placeholder="选择账号"
          style="max-width: 200px; margin-right: 20px;"
          @change="handelChangeAccount"
        >
          <el-option
            v-for="item in wcconfigs"
            :key="item.id"
            :label="item._serialized"
            :value="item.id"
          />
        </el-select>

        <!-- 状态过滤 -->
        <el-select
          v-model="statusFilter"
          placeholder="状态过滤"
          style="max-width: 150px; margin-right: 20px;"
          @change="handleStatusChange"
        >
          <el-option label="全部" value="" />
          <el-option
            v-for="status in statusOptions"
            :key="status"
            :label="status"
            :value="status"
          />
        </el-select>

        <!-- 添加按钮 -->
        <el-button
          type="primary"
          class="el-icon-plus"
          :disabled="listLoading"
          style="margin-left: auto;"
          @click="handleAction('create', '添加')"
        >
          添加
        </el-button>
      </el-header>

      <el-main>
        <el-table
          v-loading="listLoading"
          :data="data"
          border
          fit
          highlight-current-row
          style="width: 100%; height: calc(100vh - 150px);"
          @sort-change="handleSort"
        >
          <el-table-column prop="whatsapp_number" label="WhatsApp 号码">
            <template slot-scope="scope">
              <div>{{ scope.row.whatsapp_number }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="prompt" label="prompt" width="180">
            <template slot-scope="scope">
              <el-input v-model="scope.row.prompt" type="textarea" :rows="5" placeholder="prompt" />
            </template>
          </el-table-column>
          <el-table-column prop="other_info" label="其他信息" width="180">
            <template slot-scope="scope">
              <div>{{ scope.row.other_info }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template slot-scope="scope">
              <el-tag :type="statusType(scope.row.status)">
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="send_success" label="发送成功" width="100">
            <template slot-scope="scope">
              <div>{{ scope.row.send_success ? '是' : '否' }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="send_count" label="发送次数" width="100">
            <template slot-scope="scope">
              <div>{{ scope.row.send_count }}</div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="200" fixed="right">
            <template slot-scope="scope">
              <el-button
                size="mini"
                icon="el-icon-edit"
                type="warning"
                plain
                @click="handleAction('edit', scope.row)"
              >
                修改
              </el-button>
              <el-button
                size="mini"
                icon="el-icon-delete"
                type="danger"
                plain
                @click="handleAction('delete', scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          v-if="data.length"
          background
          class="mt-pagination"
          :current-page="page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </el-main>
    </el-container>

    <!-- 添加/编辑任务的对话框 -->
    <el-dialog
      append-to-body
      :title="title"
      :width="width"
      :visible.sync="innerDialogVisible"
      :close-on-click-modal="false"
    >
      <el-form :model="temp" label-position="left" label-width="120px">
        <el-form-item label="prompt ID" prop="prompt">
          <el-input v-model="temp.prompt" type="textarea" :rows="5" placeholder="prompt" />
        </el-form-item>
        <el-form-item label="WhatsApp 号码" prop="whatsapp_number">
          <el-input
            v-model="temp.whatsapp_number"
            type="textarea"
            placeholder="输入多个号码，用逗号、分号或换行符分隔"
            :rows="5"
          />
        </el-form-item>
        <el-form-item label="其他信息" prop="other_info">
          <el-input v-model="temp.other_info" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="innerDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </span>
    </el-dialog>

    <!-- 查看任务详情的对话框 -->
    <el-dialog
      append-to-body
      title="任务详情"
      :width="width"
      :visible.sync="viewDialogVisible"
      :close-on-click-modal="false"
    >
      <el-descriptions bordered>
        <el-descriptions-item label="消息模板">
          {{ currentTask.prompt }}
        </el-descriptions-item>
        <el-descriptions-item label="WhatsApp 号码">
          {{ currentTask.whatsapp_number }}
        </el-descriptions-item>
        <el-descriptions-item label="其他信息">
          {{ currentTask.other_info }}
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          {{ currentTask.status }}
        </el-descriptions-item>
        <el-descriptions-item label="发送成功">
          {{ currentTask.send_success ? '是' : '否' }}
        </el-descriptions-item>
        <el-descriptions-item label="发送次数">
          {{ currentTask.send_count }}
        </el-descriptions-item>
      </el-descriptions>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="viewDialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { Get, Post, Put, Delete } from '@/api/crm/whatsapptask'
import { Get as GetCRMM } from '@/api/crm/crmm'
import qs from 'qs'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}

export default {
  name: 'WhatsappTask',
  data() {
    return {
      data: [],
      listLoading: false,
      kwInput: '',
      statusFilter: '',
      order_by: '',
      order_desc: '',
      // pagination
      pagesize: 10,
      page: 1,
      total: 0,
      action: null,
      dialogVisible: false,
      title: '',
      inputVisible: false,
      inputValue: '',
      temp: {
        prompt: '',
        whatsapp_number: '',
        other_info: '',
        status: '未开始',
        send_success: false,
        send_count: 0
      },
      prompts: [], // 消息模板列表，需要从后台获取
      width: '640px',
      innerDialogVisible: false,
      viewDialogVisible: false,
      currentTask: {},
      statusOptions: ['未开始', '进行中', '已完成', '失败'],
      wcconfigs: [],
      wc_id: ''
    }
  },
  created() {
    this.getWcConfigs()
    this.getList()
  },
  methods: {
    handelChangeAccount() {
      this.page = 1
      this.getList()
    },
    getWcConfigs() {
      this.listLoading = true
      GetCRMM(null, qs.stringify({
        pagesize: 100,
        table_name: 'WhatsappConfig',
        page: 1
      }))
        .then(response => {
          this.wcconfigs = response.data.data
          // 如果获取到,获取chats
          if (this.wcconfigs.length) {
            this.wc_id = this.wcconfigs[0].id
            this.getChats()
          }
          this.listLoading = false
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    resetTemp() {
      this.temp = {
        prompt: '',
        whatsapp_number: '',
        other_info: '',
        status: '未开始',
        send_success: false,
        send_count: 0
      }
    },
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        whatsappconfig_id: this.wc_id,
        status: this.statusFilter,
        pagesize: this.pagesize,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.scrollTop()
          this.data = response.data.data.map(task => {
            return {
              ...task,
              prompt_name: this.getpromptName(task.prompt),
              whatsapp_number: task.whatsapp_number
            }
          })
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'create':
          this.title = '添加任务'
          this.resetTemp()
          this.innerDialogVisible = true
          break
        case 'delete':
          this.$confirm(`确认要删除任务：${row.whatsapp_number} 吗？`, '提示', {
            type: 'warning'
          }).then(() => {
            Delete(row.id).then(() => {
              this.notify('删除成功')
              this.getList()
            })
          }).catch(() => {})
          break
        case 'edit':
          this.title = `修改任务：${row.whatsapp_number}`
          Object.keys(this.temp).forEach(key => {
            if (row[key] !== undefined) this.temp[key] = row[key]
          })
          this.temp.id = row.id
          this.innerDialogVisible = true
          break
        case 'view':
          this.currentTask = row
          this.viewDialogVisible = true
          break
      }
    },
    confirm() {
      const _data = this.temp
      if (!_data.prompt || _data.whatsapp_number === '') {
        this.$message.error('请填写完整的任务信息')
        return
      }
      switch (this.action) {
        case 'create':
          Post(_data)
            .then(() => {
              this.innerDialogVisible = false
              this.getList()
              this.notify('添加成功')
            }).catch(err => {
              console.log(err)
              this.$message.error('添加失败')
            })
          break
        case 'edit':
          Put(_data.id, _data)
            .then(() => {
              this.innerDialogVisible = false
              this.getList()
              this.notify('更新成功')
            }).catch(err => {
              console.log(err)
              this.$message.error('更新失败')
            })
          break
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    handleStatusChange() {
      this.page = 1
      this.getList()
    },
    scrollTop() {
      window.scrollTo(0, 0)
    },
    statusType(status) {
      switch (status) {
        case '未开始':
          return 'info'
        case '进行中':
          return 'primary'
        case '已完成':
          return 'success'
        case '失败':
          return 'danger'
        default:
          return 'default'
      }
    }
  }
}
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}

.top >>> .el-select .el-input {
  width: 350px;
}

.top >>> .input-with-select .el-input-group__prepend {
  background-color: #fff;
}

.top {
  padding-left: 20px;
  margin-bottom: 30px;
  margin-top: 28px;
}

.input-with-select {
  width: calc(100% - 200px);
}

.add-btn {
  float: right;
  margin-right: 20px;
  width: 150px;
}

.mt-pagination {
  float: right;
  margin-top: 5px;
}

.app-container >>> .el-dialog {
  margin-top: 48px !important;
  margin-bottom: 68px;
}

.mt-dialog >>> .el-transfer-panel {
  width: calc(50% - 60px);
}

.mt-form >>> .el-select {
  width: 100%;
}

.mt-form >>> .el-input__inner {
  width: 100%;
}

.mt-dialog >>> .el-dialog {
  margin-top: 60px;
}

.mt-dialog >>> .el-dialog__body {
  padding-bottom: 100px;
}
</style>
